package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.redis.service.ISecurityRedisService;
import cn.wolfcode.luowowo.redis.util.RedisKeys;
import cn.wolfcode.luowowo.util.JsonResult;
import cn.wolfcode.luowowo.util.RequestUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 防刷拦截器
 */
public class BrushProofInterceptor implements HandlerInterceptor {
    @Autowired
    private ISecurityRedisService securityRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if(!(handler instanceof HandlerMethod)){
            return  true;
        }

        //防刷验证
        //获得请求接口url：http://localhost:8080/xxx/xxx
        String url = request.getRequestURI().substring(1);
        //拿到请求的ip
        String ip = RequestUtil.getIPAddress();

        //设计Redis的key ：brush_proof:ip   value
        String key = RedisKeys.BRUSH_PROOF.join(url, ip);

        //调用方法，判断是否超时
        if(!securityRedisService.isAllowBrush(key)){
            //表示已经超频了
            //可以做一些额外的处理，比如，加入黑名单
            response.setContentType("text/json;charset=UTF-8"); //响应格式
            //响应内容
            response.getWriter().write(JSON.toJSONString(JsonResult.error(500, "请勿频繁访问","谢谢咯")));
            return false;
        }
        return true;
    }
}
